package com.lizemin.exception;

import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.json.JSONUtil;
import com.lizemin.resp.ApiResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.cloud.gateway.support.NotFoundException;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

@Slf4j
@Component
@Order(-1) // 优先级高于默认的异常处理器，只能处理网关抛出的异常，不能处理微服务抛出的异常
public class GlobalErrorWebExceptionHandler implements ErrorWebExceptionHandler {

    @Override
    public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
        ServerHttpResponse response = exchange.getResponse();
        log.error("发生了异常：{}", ExceptionUtil.stacktraceToString(ex));
        if (response.isCommitted()) {
            //对于已经committed(提交)的response，就不能再使用这个response向缓冲区写任何东西
            return Mono.error(ex);
        }

        // 设置响应状态码
        if (ex instanceof NotFoundException) {
            response.setStatusCode(HttpStatus.NOT_FOUND);
        }

        // 设置响应内容类型
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);

        // 封装统一的响应格式
        ApiResponse apiResponse = ApiResponse.fail(ex.getMessage());

        // 将响应写入到响应体
        return response.writeWith(Mono.just(response.bufferFactory()
            .wrap(JSONUtil.toJsonStr(apiResponse).getBytes(StandardCharsets.UTF_8))));
    }
}